package com.ford.cn.csre.scenerio.domain.vo;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.Arrays;
import java.util.Date;
import java.util.Properties;

@Slf4j
public class KafkaSource implements SourceFunction<Alarm> {
    private Boolean running = true;
    @Override
    public void run(SourceContext<Alarm> sourceContext) throws Exception {
        Properties properties = new Properties();
        properties.put("bootstrap.servers", "175.27.156.59:9092");//xxx是服务器集群的ip
        properties.put("group.id", "jd-group");
        properties.put("enable.auto.commit", "true");
        properties.put("auto.commit.interval.ms", "1000");
        properties.put("auto.offset.reset", "latest");
        properties.put("session.timeout.ms", "30000");
        properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(properties);
        kafkaConsumer.subscribe(Arrays.asList("recommender"));
        while (running) {
            ConsumerRecords<String, String> records = kafkaConsumer.poll(100);
            for (ConsumerRecord<String, String> record : records) {
                log.info("offset = {}, value = {}", record.offset(), record.value());
                try {
                    Alarm alarm = JSON.parseObject(record.value(), Alarm.class);
                    alarm.setEventTime(new Date());
                    sourceContext.collect(alarm);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @Override
    public void cancel() {
        running = false;
    }
}
